
const app = getApp();
Page({
  data: {
    authorize: false,
    dataSessionId: null,
    indicatorDots: true,
    idIponeXFlag: false,
    autoplay: true,
    interval: 4000,
    duration: 500,
    hot: [],
    discover: [],
    test: [],
    currentTab: 0,
    show: false,
    showAn:false,
    showPullMask:false,
    alreadyTips: false,
    isIOSVerHighPage:false,
    isIOSPage:false,
    showFlag:false,
    userInfo:'',
    levels:''

  },
  onLoad: function (options) {    
    if (options.task_intval_friend){
      wx.setStorageSync('task_invite_friend', options.task_intval_friend);
    }
    if (options.hasOwnProperty('shareTpl')) {
      wx.reportAnalytics('share_click', {
        tpl_index: options.shareTpl * 1,
      });
    }
    this.setData({
      num: 1,
    })   

  },
  //用户登录
  getuserinfo(ops) {
    const loginParams = ops.detail;
    if (ops.detail.errMsg === "getUserInfo:fail auth deny") {
      wx.showToast({ title: '请点击允许以获取信息!', icon: 'none' })
      return;
    }
    app.callLogin(loginParams).then(data => {
      this.setData({
        authorize: false,
        dataSessionId: wx.getStorageSync('sessionid_pro'),
      });
      wx.hideLoading();
      this.getHomepage()
      wx.showToast({ title: '登录成功' });
    })
    
  },
  getHomepage() {
    wx.request({
      url: app.data.commonUrl + app.data.homepage,
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": 'Bearer ' + wx.getStorageSync('sessionid_pro'),
      },
      method: 'GET',
      success: res => {
        if (res.data.code === 0) {
          this.setData({
            userInfo: res.data.result.userinfo

          })
          if (res.data.result.userinfo) {
            let coin = res.data.result.userinfo.coin_total;         
            //方法调用
            app.judgeGrade(coin);
            this.setData({
              levels: app.data.levels
            })
          }
        }
      }
    })
  },
  onShow() {
    app.data.countGlobal.setEnv(app.data.optGlobal);
    app.data.countGlobal.setOpenid(wx.getStorageSync('openid'));
    let session_id = wx.getStorageSync('sessionid_pro');
    if (!session_id) {
      this.setData({
        authorize: true
      })
    } else {
      this.setData({
        authorize: false
      })
    }
    this.setData({
      idIponeXFlag: app.data.isIPhoneX,
      alreadyTips: wx.getStorageSync('alreadyTips'),
      isIOSVerHighPage: app.data.isIOSVerHigh,
      isIOSPage: app.data.isIOS,
      dataSessionId: session_id,
      currentTab:0
    })
    
    //获取游戏的内容的接口
    wx.request({
      url: app.data.commonUrl + '/Server/GameCenter/index',
      success: res => {
        if (res.data.code === 0) {
          const {hot, discover,test } = res.data.result;
          this.setData({hot, discover ,test})
        }
      }
    })

    
  },
  onShareAppMessage(res) {
    const index = ~~(Math.random() * app.data.shareTpl.length)
      , tplIndex = index + 1;
    return {
      title: app.data.shareTpl[index],
      path: `/pages/index/index?shareTpl=${tplIndex}`,
      imageUrl: `/resourse/ad${tplIndex}.jpg`,
      success: function (res) {
        wx.reportAnalytics('share_open', {
          tpl_index: tplIndex,
        });
      },
      fail: function (res) {

      }
    }
  },
  //点击每个游戏需判断是否有tempad，有的话直接跳转，没有则预览图片
  openUrlFn(e) {
    let tempad = e.currentTarget.dataset.ad,
      tempAppId = e.currentTarget.dataset.appid,
      id = e.currentTarget.dataset.id,
      title = e.currentTarget.dataset.title,
      ext_data = e.currentTarget.dataset.ext_data,
      index = e.currentTarget.dataset.idx,
      name = e.currentTarget.dataset.name;
    //不存在ad字段，调用navigateToMiniProgram
    if (tempad == '' || tempad == null) {
      wx.showLoading({ title: '正在打开' })

      try {
        if (ext_data == '' || ext_data == undefined) {
          ext_data = {};
        } else {
          ext_data = JSON.parse(ext_data);
        }
      } catch (e) {
        wx.hideLoading();
        wx.showToast({
          title: '后台参数错误',
          icon:'none'
        })
        return false;
        console.log(e);
      }
       
      wx.navigateToMiniProgram({
        appId: tempAppId,
        path      : e.currentTarget.dataset.path,
        extraData : ext_data,
        envVersion: 'release',
        success:res =>{
          app.data.countGlobal.unitCount(name, index,tempAppId)
          //从“我的”页面点击分享后进来的
          if (wx.getStorageSync('task_invite_friend')){
            this.taskFn({ 
              appflag: app.data.appflag, 
              task_name: 'share', 
              openid: wx.getStorageSync('task_invite_friend')
            },0)
            wx.removeStorageSync('task_invite_friend')
          }else{ 
            //从“我的”页面点击进入5款不同游戏
            let day = new Date();
            day.setTime(day.getTime());
            let s2 = day.getFullYear() + "-" + (day.getMonth() + 1) + "-" + day.getDate(),
              enter_game = wx.getStorageSync('enter_game_num_' + s2);
            if (enter_game) {
              if (enter_game.includes(id)) {
                wx.setStorageSync('enter_game_num_' + s2, enter_game)
                this.setData({
                  showFlag: false
                })
              } else {
                enter_game.push(id)
                this.taskFn({ appflag: app.data.appflag,task_name: 'enter_game' }, 1)  
                wx.setStorageSync('enter_game_num_' + s2, enter_game)
                this.setData({
                  showFlag: true
                })
              }
            } else {
              this.taskFn({ task_name: 'enter_game' }, 1)  
              wx.setStorageSync('enter_game_num_' + s2, [id])
              this.setData({
                showFlag: true
              })
            }            
                         
          }
          //默认进来小游戏的
          wx.hideLoading();
          //打开成功
          wx.reportAnalytics('click_game', {
            game_id: id,
            game_name: title
          });

        },
        fail(res) {
          wx.hideLoading();
          console.log('失败', res)
          
        }
      })

    } else {
      wx.previewImage({
        current: tempad, // 当前显示图片的http链接  
        urls: [tempad] // 需要预览的图片http链接列表  
      })
      wx.reportAnalytics('click_game', {
        game_id: id,
        game_name: title
      });
    }
  },
  //分享和进入游戏需要请求task接口
  taskFn(data,num){
    console.log(data, num)
    wx.request({
      url: app.data.commonUrl + app.data.taskUrl,
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": 'Bearer ' + this.data.dataSessionId,
      },
      method: 'GET',
      data: data,
      success: res => {
        if (num == 1 && app.data.game_current_num <= 4 && this.data.showFlag) {
          app.data.showResiveFlag = true;
          app.data.showResiveTip = '进入游戏成功';
          app.data.showResiveIcon = 100;
        } 
       
      }
    })
  },
  //头部选项卡（左右滑动效果）
  bindChange: function (e) {
    let day = new Date();
    day.setTime(day.getTime());
    let s2 = day.getFullYear() + "-" + (day.getMonth() + 1) + "-" + day.getDate(),
        tip = wx.getStorageSync('tip_' + s2);
    if (tip) {
      if (tip == 0) {
        this.setData({
          show: false,
          showAn: false
        })
      }
    } else {
      if (!this.data.isIOSPage && e.detail.current == 1) {
        this.setData({
          showAn: true,
        })
      } else if (this.data.isIOSVerHighPage && e.detail.current == 1) {
        this.setData({
          show: true
        })
      } else {
        this.setData({
          show: false,
          showAn: false
        })
      }
      wx.setStorageSync('tip_' + s2, 1)
    }
    this.setData({ currentTab: e.detail.current });
  },
  //头部选项卡（点击切换效果）
  swichNav: function (e) {
    let day = new Date();
    day.setTime(day.getTime());
    let s2 = day.getFullYear() + "-" + (day.getMonth() + 1) + "-" + day.getDate(),
        tip = wx.getStorageSync('tip_' + s2);
    if(tip){
      if(tip==0){
        this.setData({
          show: false,
          showAn:false
        })
      }
    }else{
      if (!this.data.isIOSPage && e.target.dataset.current == 1) {
        this.setData({
          showAn: true,
        })
      } else if (this.data.isIOSVerHighPage && e.target.dataset.current == 1) {
        this.setData({
          show: true
        })
      } else {
        this.setData({
          show: false,
          showAn: false
        })
      }
      wx.setStorageSync('tip_' + s2,1)
    }    
    
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      this.setData({
        currentTab: e.target.dataset.current
      })
    }
  },
  hideMask(){
    this.setData({
      show: false,
      showAn:false,
      showPullMask:true
    })
  },
  hidePullMask() {
    this.setData({
      showPullMask:false,
    })
    
  },
  showPullMask(){ 
    this.setData({
      showPullMask: true
    })     
    
  },
  
})



